package com.example.greedysnake;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.SurfaceHolder;
import android.view.View;
import com.example.greedysnake.activity.SnakeAboutActivity;
import com.example.greedysnake.activity.SnakeLevelActivity;
import com.example.greedysnake.activity.SnakeScoreActivity;
import com.example.greedysnake.datas.SnakeGamingData;
import com.example.greedysnake.enums.GamingStatus;
import com.example.greedysnake.enums.MovePosition;
import com.example.greedysnake.views.SnakeGamingSurfaceView;

import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = MainActivity.class.getSimpleName();
    SnakeGamingSurfaceView surfaceView;
    SnakeGamingData snakeGamingData;

    Timer timer;
    SnakeMoveTimerTask snakeMoveTimerTask;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        snakeGamingData = new ViewModelProvider(this, new ViewModelProvider.AndroidViewModelFactory(getApplication())).get(SnakeGamingData.class);
        Log.i(TAG, "onCreate: " + snakeGamingData);
        surfaceView = findViewById(R.id.surfaceView);

        surfaceView.getHolder().addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(@NonNull SurfaceHolder holder) {
                // 第一次绘制
                snakeGamingData.init(holder.getSurfaceFrame().width() / 16);
                surfaceView.update(snakeGamingData.updateCurrentGamingData());
            }

            @Override
            public void surfaceChanged(@NonNull SurfaceHolder holder, int format, int width, int height) {
            }

            @Override
            public void surfaceDestroyed(@NonNull SurfaceHolder holder) {
            }
        });

        timer = new Timer();
        Log.i(TAG, "level: " + snakeGamingData.getLevel());
        snakeMoveTimerTask = new SnakeMoveTimerTask();
        timer.schedule(snakeMoveTimerTask, 1000L, snakeGamingData.getLevel());

        // 游戏状态
        snakeGamingData.getGamingStatus().observe(this, gamingStatus -> {
            switch (gamingStatus){
                case GOING:{}break;
                case FAILED:{
                    timer.cancel();
                    snakeMoveTimerTask.setRunning(false);
                    AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this)
                            .setTitle("oooh 撞到啦!")
                            .setMessage("是否重新开始?")
                            .setPositiveButton("确定", (dialog, which) -> {
                                snakeGamingData.reInit();
                                surfaceView.update(snakeGamingData.updateCurrentGamingData());
                                snakeGamingData.getGamingStatus().postValue(GamingStatus.RESTART);
                            })
                            .setNegativeButton("取消", (dialog, which) -> {

                            });
                    snakeGamingData.saveScore();
                    alertDialog.show();
                }break;
                case RESTART:{
                    timer = new Timer();
                    snakeMoveTimerTask = new SnakeMoveTimerTask();
                    timer.schedule(snakeMoveTimerTask, 1000L, snakeGamingData.getLevel());
                }break;
                default:
            }
        });

    }

    // 自动移动
    class SnakeMoveTimerTask extends TimerTask {

        boolean isRunning = true;

        @Override
        public void run() {
            if (isRunning){
                if(snakeGamingData.autoMove()){
                    surfaceView.update(snakeGamingData.updateCurrentGamingData());
                }else {
                    // 后台线程使用 postValue
                    snakeGamingData.getGamingStatus().postValue(GamingStatus.FAILED);
                    Log.i(TAG, "game over!!!");
                }
            }
        }

        public void setRunning(boolean running) {
            isRunning = running;
        }
    }

    // 移动
    public void up(View view){
        snakeGamingData.setMovePosition(MovePosition.TOP);
    }
    public void down(View view){
        snakeGamingData.setMovePosition(MovePosition.BOTTOM);
    }
    public void left(View view){
        snakeGamingData.setMovePosition(MovePosition.LEFT);
    }
    public void right(View view){
        snakeGamingData.setMovePosition(MovePosition.RIGHT);
    }


    // 菜单
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater menuInflater = new MenuInflater(this);
        menuInflater.inflate(R.menu.snake_menu, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()){
            case R.id.snake_restart: {
                snakeGamingData.reInit();
                surfaceView.update(snakeGamingData.updateCurrentGamingData());
                snakeGamingData.getGamingStatus().postValue(GamingStatus.RESTART);
            }break;
            case R.id.snake_score: {
                startActivity(new Intent(this, SnakeScoreActivity.class));
            }break;
            case R.id.snake_about:{
                startActivity(new Intent(this, SnakeAboutActivity.class));
            }break;
            case R.id.snake_level:{
                startActivity(new Intent(this, SnakeLevelActivity.class));
            }break;
            default:
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }
}